import { nextTick } from 'vue'

/**
 * 解析参数字符串或对象
 */
export const parseParams = (params: any) => {
  if (!params) return {}
  return typeof params === 'string' ? JSON.parse(params) : params
}

/**
 * 推断时间范围类型
 */
export const inferTimeRangeType = (timeStart: string | null, timeEnd: string | null, existingType?: string): string => {
  // 如果有现存的 time_range_type，且不是默认的 all，则优先使用
  if (existingType && existingType !== 'all') {
    return existingType
  }
  
  // 如果时间都为 null，说明是"全部"
  if (timeStart === null && timeEnd === null) {
    return existingType || 'all'
  }
  
  // 如果有具体时间范围，需要判断类型
  if (timeStart && timeEnd) {
    const start = new Date(timeStart)
    const end = new Date(timeEnd)
    const now = new Date()
    const yesterday = new Date(now)
    yesterday.setDate(yesterday.getDate() - 1)
    yesterday.setHours(0, 0, 0, 0)
    const yesterdayEnd = new Date(yesterday)
    yesterdayEnd.setHours(23, 59, 59, 999)
    
    // 判断是否是昨天
    if (start.getTime() >= yesterday.getTime() && end.getTime() <= yesterdayEnd.getTime()) {
      return 'yesterday'
    } else {
      // 判断是否是最近7天
      const sevenDaysAgo = new Date(now)
      sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)
      if (start.getTime() >= sevenDaysAgo.getTime()) {
        return 'recent'
      } else {
        // 判断是否是上月
        const lastMonthStart = new Date(now.getFullYear(), now.getMonth() - 1, 1)
        const lastMonthEnd = new Date(now.getFullYear(), now.getMonth(), 0, 23, 59, 59, 999)
        if (start.getTime() >= lastMonthStart.getTime() && end.getTime() <= lastMonthEnd.getTime()) {
          return 'last_month'
        } else {
          return 'custom'
        }
      }
    }
  }
  
  return 'all'
}

/**
 * 过滤输出格式，确保只返回支持的格式
 */
export const filterOutputFormats = (formats: any): string[] => {
  if (!formats) return ['html']
  
  const supportedFormats = ['html', 'excel']
  const parsed = typeof formats === 'string' ? JSON.parse(formats) : formats
  
  if (Array.isArray(parsed)) {
    return parsed.filter(format => supportedFormats.includes(format))
  }
  
  return ['html']
}

/**
 * 从运行记录数据构建表单数据
 */
export const buildFormDataFromRun = async (runData: any, api: any) => {
  // 解析参数
  const params = parseParams(runData.params)
  
  // 获取输出格式：优先从运行记录中获取，如果没有则从配置中获取
  let outputFormats = ['html']
  if (runData.output_formats) {
    // 从运行记录中获取
    outputFormats = filterOutputFormats(runData.output_formats)
  } else if (runData.report_config_id) {
    // 从配置中获取
    try {
      const configResponse = await api.get(`/reports/configs/${runData.report_config_id}`)
      if (configResponse.data.success && configResponse.data.data) {
        const config = configResponse.data.data
        if (config.output_formats) {
          outputFormats = filterOutputFormats(config.output_formats)
        }
      }
    } catch (configError) {
      console.warn('获取配置输出格式失败，使用默认值', configError)
    }
  }
  
  return {
    template_code: runData.template_code,
    title: runData.title || '',
    params: params,
    output_formats: outputFormats,
    notify_params: runData.notify_params || {
      send_notification: false,
      channels: [],
      webhook_id: null,
      wecom_mention: null
    },
    data_source_id: runData.data_source_id || null
  }
}

/**
 * 从配置数据构建表单数据
 */
export const buildFormDataFromConfig = (configData: any) => {
  return {
    config_name: configData.config_name || '',
    template_code: configData.template_code || '',
    is_active: !!configData.is_active,
    schedule_enabled: !!configData.schedule_enabled,
    schedule_cron: configData.schedule_cron || '',
    output_formats: filterOutputFormats(configData.output_formats),
    params: parseParams(configData.params),
    notify_on_success: !!configData.notify_on_success
  }
}

/**
 * 重建时间范围对象（用于模板参数）
 */
export const rebuildTimeRangeForParams = (params: any) => {
  if (!params) return params
  
  const result = { ...params }
  
  const normalizeTimeValue = (value: any) => {
    if (value === undefined) return undefined
    if (value === '' || value === null) return null
    return value
  }
  
  const extractTimeRange = () => {
    const candidates = [
      { start: result.time_start, end: result.time_end, type: result.time_range_type },
      { start: result.start_time, end: result.end_time, type: result.time_range_type },
      { start: result.created_start, end: result.created_end, type: result.time_range_type },
      result.time_range,
      result.time_filter,
      result.source_tables,
      result.target_table_config
    ]
    
    for (const candidate of candidates) {
      if (!candidate || typeof candidate !== 'object') continue
      const start = normalizeTimeValue(candidate.time_start)
      const end = normalizeTimeValue(candidate.time_end)
      if (start !== undefined || end !== undefined) {
        return {
          start: start ?? null,
          end: end ?? null,
          type: candidate.time_range_type
        }
      }
    }
    
    return {
      start: null,
      end: null,
      type: result.time_range_type ?? 'all'
    }
  }
  
  const { start, end, type } = extractTimeRange()
  const inferredType = inferTimeRangeType(start, end, type)
  
  const writeTimeRange = (target: any) => {
    if (!target || typeof target !== 'object') return target
    return {
      ...target,
      time_range_type: inferredType,
      time_start: start,
      time_end: end
    }
  }
  
  result.time_range_type = inferredType
  result.time_start = start
  result.time_end = end
  result.time_range = {
    time_range_type: inferredType,
    time_start: start,
    time_end: end
  }
  
  if (result.time_filter && typeof result.time_filter === 'object') {
    result.time_filter = writeTimeRange(result.time_filter)
  }
  
  if (result.source_tables && typeof result.source_tables === 'object') {
    result.source_tables = writeTimeRange(result.source_tables)
  }
  
  if (result.target_table_config && typeof result.target_table_config === 'object') {
    result.target_table_config = writeTimeRange(result.target_table_config)
  }
  
  return result
}
